package com.example.GlobalExeption;

import com.example.Entity.Vo.APIResult;
import com.example.Utils.APIResultUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

/**
 * @author 须尽欢
 * &#064;date  2023/02/11 17:18
 * &#064;description  SaToken全局异常拦截
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    /**
     * 全局异常拦截，鉴权失败不会报错，会返回给前端报错原因
     * @param e 错误信息
     * @return APIResult
     */
    @ExceptionHandler
    public APIResult handlerException(Exception e) {
        System.out.println(e.getMessage());
        if(Objects.equals(e.getMessage(), "请重新登录")){
            return APIResult.error("请重新登录",1001);
        }
        else if (Objects.equals(e.getMessage(), "未能读取到有效Token")){
            return APIResult.error("登录过期，请重新登录",1001);
        }
        else{
            logger.error("发生错误："+e.getMessage());
            return APIResultUtils.error("发生错误"+e.getMessage(),e.getMessage());
        }
    }
}
